package lesson03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLoock 代替synchronized
 */
public class ReentrantLoock3 {

    ReentrantLock lock = new ReentrantLock();
    public void m1(){
        for (int i = 0; i < 10; i++) {
            try {
                lock.lock();
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
                if (i == 2){
                    m2();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }

    /*
    synchronized void m2(){
        System.out.println("m2....");
    }
    */

    public void m2(){
        try {
            lock.lock();
            System.out.println("m2....");
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        ReentrantLoock3 reeen = new ReentrantLoock3();
        Thread t1 = new Thread(reeen::m1);
        t1.start();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // new Thread(reeen::m2).start(); // 这样 m1用ReentrantLock，m2用synchronized// 是没意义的，不是锁同一个对象

    }
}
